{% extends 'assets/base.html' %}
{% load static %}

{% block title %}AI推荐列表{% endblock %}

{% block extra_css %}
<style>
.recommendation-card {
    border-left: 4px solid #28a745;
    transition: all 0.3s ease;
}
.recommendation-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.recommendation-card.priority-high {
    border-left-color: #dc3545;
}
.recommendation-card.priority-urgent {
    border-left-color: #fd7e14;
}
.recommendation-card.priority-medium {
    border-left-color: #ffc107;
}
.recommendation-card.priority-low {
    border-left-color: #6c757d;
}
.confidence-score {
    font-weight: bold;
    color: #007bff;
}
.filter-card {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-lightbulb"></i> AI推荐列表</h2>
        <div class="btn-group">
            <a href="{% url 'assets:ai_dashboard' %}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> 返回仪表板
            </a>
            <button type="button" class="btn btn-primary" onclick="generateRecommendations()">
                <i class="fas fa-magic"></i> 生成新推荐
            </button>
        </div>
    </div>

    <!-- 筛选器 -->
    <div class="filter-card">
        <form method="get" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">推荐类型</label>
                <select name="type" class="form-select">
                    <option value="">全部类型</option>
                    {% for value, label in recommendation_types %}
                    <option value="{{ value }}" {% if current_filters.type == value %}selected{% endif %}>
                        {{ label }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">优先级</label>
                <select name="priority" class="form-select">
                    <option value="">全部优先级</option>
                    {% for value, label in priorities %}
                    <option value="{{ value }}" {% if current_filters.priority == value %}selected{% endif %}>
                        {{ label }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">状态</label>
                <select name="status" class="form-select">
                    <option value="all" {% if current_filters.status == 'all' %}selected{% endif %}>全部状态</option>
                    <option value="unread" {% if current_filters.status == 'unread' %}selected{% endif %}>未读</option>
                    <option value="accepted" {% if current_filters.status == 'accepted' %}selected{% endif %}>已接受</option>
                    <option value="dismissed" {% if current_filters.status == 'dismissed' %}selected{% endif %}>已忽略</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">&nbsp;</label>
                <div class="d-grid">
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="fas fa-search"></i> 筛选
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 推荐列表 -->
    <div class="row">
        {% if page_obj %}
            {% for recommendation in page_obj %}
            <div class="col-md-6 mb-3">
                <div class="card recommendation-card priority-{{ recommendation.priority }}" data-id="{{ recommendation.id }}">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h5 class="card-title mb-0">{{ recommendation.title }}</h5>
                            <div class="btn-group btn-group-sm">
                                {% if not recommendation.is_accepted and not recommendation.is_dismissed %}
                                <button class="btn btn-success" onclick="handleRecommendation({{ recommendation.id }}, 'accept')" title="接受">
                                    <i class="fas fa-check"></i>
                                </button>
                                <button class="btn btn-secondary" onclick="handleRecommendation({{ recommendation.id }}, 'dismiss')" title="忽略">
                                    <i class="fas fa-times"></i>
                                </button>
                                {% endif %}
                            </div>
                        </div>
                        
                        <p class="card-text text-muted">{{ recommendation.description }}</p>
                        
                        <div class="row mb-3">
                            <div class="col-6">
                                <small class="text-muted">推荐类型:</small><br>
                                <span class="badge bg-info">{{ recommendation.get_recommendation_type_display }}</span>
                            </div>
                            <div class="col-6">
                                <small class="text-muted">优先级:</small><br>
                                <span class="badge bg-{{ recommendation.priority }}">{{ recommendation.get_priority_display }}</span>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-6">
                                <small class="text-muted">置信度:</small><br>
                                <span class="confidence-score">{{ recommendation.confidence_score|floatformat:1 }}</span>
                            </div>
                            <div class="col-6">
                                <small class="text-muted">创建时间:</small><br>
                                <small>{{ recommendation.created_at|date:"Y-m-d H:i" }}</small>
                            </div>
                        </div>
                        
                        {% if recommendation.asset %}
                        <div class="mb-2">
                            <small class="text-muted">关联资产:</small><br>
                            <a href="{% url 'assets:asset_detail' recommendation.asset.pk %}" class="text-decoration-none">
                                {{ recommendation.asset.name }} ({{ recommendation.asset.asset_number }})
                            </a>
                        </div>
                        {% endif %}
                        
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                {% if recommendation.is_accepted %}
                                <span class="badge bg-success"><i class="fas fa-check"></i> 已接受</span>
                                {% elif recommendation.is_dismissed %}
                                <span class="badge bg-secondary"><i class="fas fa-times"></i> 已忽略</span>
                                {% elif not recommendation.is_read %}
                                <span class="badge bg-warning"><i class="fas fa-envelope"></i> 未读</span>
                                {% endif %}
                            </div>
                            {% if recommendation.expires_at %}
                            <small class="text-muted">
                                <i class="fas fa-clock"></i> 
                                过期时间: {{ recommendation.expires_at|date:"Y-m-d H:i" }}
                            </small>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        {% else %}
            <div class="col-12">
                <div class="text-center py-5">
                    <i class="fas fa-lightbulb fa-4x text-muted mb-3"></i>
                    <h4 class="text-muted">暂无推荐数据</h4>
                    <p class="text-muted">点击"生成新推荐"按钮来获取AI推荐</p>
                    <button type="button" class="btn btn-primary" onclick="generateRecommendations()">
                        <i class="fas fa-magic"></i> 生成推荐
                    </button>
                </div>
            </div>
        {% endif %}
    </div>

    <!-- 分页 -->
    {% if page_obj.has_other_pages %}
    <nav aria-label="推荐列表分页">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    上一页
                </a>
            </li>
            {% endif %}
            
            {% for num in page_obj.paginator.page_range %}
            {% if page_obj.number == num %}
            <li class="page-item active">
                <span class="page-link">{{ num }}</span>
            </li>
            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
            <li class="page-item">
                <a class="page-link" href="?page={{ num }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    {{ num }}
                </a>
            </li>
            {% endif %}
            {% endfor %}
            
            {% if page_obj.has_next %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    下一页
                </a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}
</div>

<!-- 生成推荐模态框 -->
<div class="modal fade" id="generateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">生成AI推荐</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="generateForm">
                    <div class="mb-3">
                        <label class="form-label">推荐类型</label>
                        <select name="type" class="form-select" required>
                            <option value="all">全部类型</option>
                            <option value="maintenance">维修推荐</option>
                            <option value="replacement">更换推荐</option>
                            <option value="optimization">优化推荐</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">指定资产 (可选)</label>
                        <select name="asset_id" class="form-select">
                            <option value="">全部资产</option>
                            <!-- 这里可以通过AJAX加载资产列表 -->
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitGenerate()">生成推荐</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 生成推荐
function generateRecommendations() {
    const modal = new bootstrap.Modal(document.getElementById('generateModal'));
    modal.show();
}

function submitGenerate() {
    const form = document.getElementById('generateForm');
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    showLoading('正在生成推荐...');
    
    fetch('{% url "assets:ai_generate_recommendations" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            showAlert('success', data.message);
            bootstrap.Modal.getInstance(document.getElementById('generateModal')).hide();
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        hideLoading();
        showAlert('error', '生成推荐失败: ' + error.message);
    });
}

// 处理推荐
function handleRecommendation(id, action) {
    const actionText = action === 'accept' ? '接受' : '忽略';
    
    if (!confirm(`确定要${actionText}这个推荐吗？`)) {
        return;
    }
    
    fetch(`/assets/ai/recommendations/${id}/handle/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            action: action
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            // 更新卡片状态
            const card = document.querySelector(`[data-id="${id}"]`);
            if (card) {
                const buttons = card.querySelector('.btn-group');
                if (buttons) buttons.remove();
                
                const statusArea = card.querySelector('.d-flex.justify-content-between.align-items-center div');
                if (action === 'accept') {
                    statusArea.innerHTML = '<span class="badge bg-success"><i class="fas fa-check"></i> 已接受</span>';
                } else {
                    statusArea.innerHTML = '<span class="badge bg-secondary"><i class="fas fa-times"></i> 已忽略</span>';
                }
            }
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        showAlert('error', '处理推荐失败: ' + error.message);
    });
}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showLoading(message) {
    const loading = document.createElement('div');
    loading.id = 'loading-overlay';
    loading.className = 'position-fixed top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center';
    loading.style.backgroundColor = 'rgba(0,0,0,0.5)';
    loading.style.zIndex = '9999';
    loading.innerHTML = `
        <div class="bg-white p-4 rounded text-center">
            <div class="spinner-border text-primary mb-2"></div>
            <div>${message}</div>
        </div>
    `;
    document.body.appendChild(loading);
}

function hideLoading() {
    const loading = document.getElementById('loading-overlay');
    if (loading) {
        loading.remove();
    }
}

function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alert = document.createElement('div');
    alert.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    alert.style.top = '20px';
    alert.style.right = '20px';
    alert.style.zIndex = '9999';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}
</script>
{% endblock %}